package com.oldfeel.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.oldfeel.utils.DialogUtil;
import com.oldfeel.utils.ImageUtil;
import com.oldfeel.utils.JsonUtil;
import com.oldfeel.utils.NetUtil;
import com.oldfeel.utils.R;
import com.oldfeel.utils.StringUtil;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 上传单张图片的fragment
 * Created by oldfeel on 4/4/15.
 */
public class UploadImageFragment extends BaseFragment {
    protected int userId;
    protected String imageUrl, fileSavePath, jsonApi, bucketName;

    protected ImageView imageView;
    protected static final int COMP_OK = 1; // 压缩完成
    protected static final int COMP_FAIL = 2; // 压缩失败
    protected File protraitFile;
    protected UploadManager uploadManager = new UploadManager();
    protected boolean isDestory;
    protected Uri origUri;
    protected int degree;
    protected OnUploadListener onUploadListener;
    protected boolean isCrop; // true 为选择图片后剪切,false 为选择图片后压缩
    protected int cropWidth; // 剪切图片的宽度

    public static UploadImageFragment newInstace(int defaultImageId, int userId, String fileSavePath, String jsonApi, String bucketName) {
        return newInstace(defaultImageId, userId, null, fileSavePath, jsonApi, bucketName);
    }

    public static UploadImageFragment newInstace(int defaultImageId, int userId, String imageUrl, String fileSavePath, String jsonApi, String bucketName) {
        UploadImageFragment fragment = new UploadImageFragment();
        fragment.defaultImageId = defaultImageId;
        fragment.userId = userId;
        fragment.imageUrl = imageUrl;
        fragment.fileSavePath = fileSavePath;
        fragment.jsonApi = jsonApi;
        fragment.bucketName = bucketName;
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        imageView = new ImageView(getActivity());
        return imageView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        imageLoader.displayImage(imageUrl, imageView, options);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getImage();
            }
        });
    }

    /**
     * 添加图片
     */
    public void getImage() {
        new AlertDialog.Builder(getActivity())
                .setTitle("添加图片")
                .setItems(R.array.add_image_type,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                switch (which) {
                                    case 0: // 手机拍照
                                        startActionCamera();
                                        break;
                                    case 1: // 从相册选择
                                        startImagePick();
                                        break;
                                    default:
                                        break;
                                }
                                dialog.cancel();
                            }
                        }).show();
    }


    /**
     * 相机拍照
     */
    protected void startActionCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, getImageTemp());
        startActivityForResult(intent, ImageUtil.REQUEST_CODE_GETIMAGE_BYCAMERA);
    }

    /**
     * @return 上传照片的绝对路径
     */
    private Uri getImageTemp() {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(fileSavePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
            showToast("无法保存上传的头像，请检查SD卡是否挂载");
            return null;
        }
        String timeStamp = StringUtil.getTimeStamp();
        // 照片命名
        String cropFileName = userId
                + "_" + timeStamp + ".jpg";
        // 裁剪头像的绝对路径
        String protraitPath = fileSavePath + "/" + cropFileName;
        protraitFile = new File(protraitPath);
        origUri = Uri.fromFile(protraitFile);
        return origUri;
    }

    /**
     * 选择图片
     */
    protected void startImagePick() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "选择图片"),
                ImageUtil.REQUEST_CODE_GETIMAGE_BYSDCARD);
    }

    public boolean isHaveImage() {
        if (protraitFile != null && protraitFile.length() != 0) {
            getToken();
            return true;
        }
        return false;
    }

    /**
     * 开始上传图片
     */
    private void getToken() {
        DialogUtil.getInstance().showPd(getActivity(), "正在上传图片...");
        NetUtil netUtil = new NetUtil(getActivity(), jsonApi);
        netUtil.setParams("bucket_name", bucketName);
        netUtil.postRequest("", new NetUtil.RequestStringListener() {

            @Override
            public void onComplete(String result) {
                if (JsonUtil.isSuccess(result)) {
                    uploadImage(JsonUtil.getData(result));
                } else {
                    DialogUtil.getInstance().cancelPd();
                    showToast(JsonUtil.getData(result));
                }
            }
        });
        netUtil.setOnNetFailListener(new NetUtil.OnNetFailListener() {
            @Override
            public void cancel() {
                showToast("取消上传");
                DialogUtil.getInstance().cancelPd();
            }

            @Override
            public void onError() {
                showToast("网络连接错误");
                DialogUtil.getInstance().cancelPd();

            }

            @Override
            public void onTimeOut() {
                showToast("连接超时");
                DialogUtil.getInstance().cancelPd();
            }
        });
    }


    /**
     * 上传照片
     */
    public void uploadImage(final String uptoken) {
        if (isDestory) {
            return;
        }
        if (protraitFile != null && protraitFile.length() != 0) {
            uploadManager.put(protraitFile, protraitFile.getName(), uptoken,
                    new UpCompletionHandler() {

                        @Override
                        public void complete(String key, ResponseInfo info,
                                             JSONObject response) {
                            DialogUtil.getInstance().cancelPd();
                            if (onUploadListener != null) {
                                onUploadListener.OnComplete(protraitFile.getName());
                            }
                        }
                    }, null);
        } else {
            DialogUtil.getInstance().cancelPd();
            showToast("选择图片出错,请重新选择");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case ImageUtil.REQUEST_CODE_GETIMAGE_BYCAMERA:
                // 有的相机拍照后图片旋转,计算出旋转角度
                degree = ImageUtil
                        .readPictureDegree(protraitFile.getAbsolutePath());
                if (isCrop) {
                    cropImage(origUri);
                } else {
                    compressionImage(origUri);
                }
                break;
            case ImageUtil.REQUEST_CODE_GETIMAGE_BYSDCARD:
                // 从相册选择的图片不旋转
                degree = 0;
                getImageTemp();
                if (isCrop) {
                    cropImage(data.getData());
                } else {
                    compressionImage(data.getData());
                }
                break;
            case ImageUtil.REQUEST_CODE_GETIMAGE_BYCROP:
                imageLoader.displayImage(
                        Uri.fromFile(protraitFile).toString(), imageView, options);
                getToken(); // 上传新照片
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void cropImage(Uri data) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        intent.putExtra("output", getImageTemp());
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", cropWidth);// 输出图片大小
        intent.putExtra("outputY", cropWidth);
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        startActivityForResult(intent, ImageUtil.REQUEST_CODE_GETIMAGE_BYCROP);
    }


    private void compressionImage(final Uri uri) {
        DialogUtil.getInstance().showPd(getActivity(), "正在压缩图片...");
        new Thread() {
            public void run() {
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(
                            getActivity().getContentResolver(), uri);
                    if (degree != 0) {
                        bitmap = ImageUtil.rotaingImageView(degree, bitmap);
                    }
                    ImageUtil.compAndSaveImage(getActivity(),
                            protraitFile.getAbsolutePath(), bitmap);
                    handler.sendEmptyMessage(COMP_OK);
                } catch (FileNotFoundException e) {
                    handler.sendEmptyMessage(COMP_FAIL);
                    e.printStackTrace();
                } catch (IOException e) {
                    handler.sendEmptyMessage(COMP_FAIL);
                    e.printStackTrace();
                }
            }

            ;
        }.start();
    }

    /**
     * 压缩图片
     */
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            DialogUtil.getInstance().cancelPd();
            switch (msg.what) {
                case COMP_OK:
                    imageLoader.displayImage(
                            Uri.fromFile(protraitFile).toString(), imageView, options);
                    break;
                case COMP_FAIL:
                    showToast("压缩失败");
                    break;
                default:
                    break;
            }
        }

        ;
    };

    @Override
    public void onDestroy() {
        DialogUtil.getInstance().cancelPd();
        isDestory = true;
        super.onDestroy();
    }

    public void setCrop(boolean isCrop, int cropWidth) {
        this.isCrop = isCrop;
        this.cropWidth = cropWidth;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public interface OnUploadListener {
        public void OnComplete(String image);
    }

    public void setOnUploadListener(OnUploadListener onUploadListener) {
        this.onUploadListener = onUploadListener;
    }
}
